<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Register_model extends Teaboy_model{
	
		public function __contruct(){
			parent::Controller();
		}
		
		public function register($name, $email, $location, $beverage="tea", $sugars=0, $milk=0, $office="SJS"){
			
			//check if the user has registered already
			$currentID = $this->userExists($email);
			if($currentID){
				return $currentID;
			}
			
			//process input
			$beverage = $this->setBeverage($beverage);
			$office = $this->setOffice($office);
			
			//add to db
			$sSQL = "INSERT INTO drinkers (name, email, location, beverage_id, sugars, milk, office_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
			$oResult = $this->db->query($sSQL, array($name, $email, $location, $beverage, $sugars, $milk, $office));
			
			//return id
			$id = $this->db->insert_id();
			if(is_int($id)){
				return $id;
			}
			
			return false;		
				
		}
		
		public function allUsers($type='emailList'){
			$aSQL['emailList'] = "SELECT name, email";
			
			if(!array_key_exists($type, $aSQL)){
				return false;
			}

			$sSQL = $aSQL[$type]." FROM drinkers";
			
			$oResult = $this->db->query($sSQL);
			
			return $oResult->result_array();
		}
		
		public function getAllPlayers($gameId){
			$sSQL = "SELECT drinkers.id as id, 
							drinkers.name as name, 
							drinkers.email as email, 
							drinkers.location as location, 
							drinkers.sugars as sugars, 
							drinkers.milk as milk, 
							beverage.type as beverage
							FROM drinkers, shakes, beverage WHERE drinkers.id = shakes.drinker_id AND shakes.game_id = ? AND shakes.beverage_id = beverage.id ORDER BY shakes.duration DESC";
			$oResult = $this->db->query($sSQL, $gameId);
			return $oResult->result_array();
		}
		
		private function userExists($email){
			
			$sSQL = "SELECT id FROM drinkers WHERE email = ?";
			$oResult = $this->db->query($sSQL, $email);
			
			if($oResult->num_rows() > 0){
				foreach($oResult->result_array() as $row){
					return $row['id'];
				}
			}
			
			return false;
		}
		
		private function setBeverage($beverage){
			return 1;
		}
		
		private function setOffice($office){
			return 1;
		}
		
		public function userIsRegistered(){
		$id = $this->input->cookie('drinkerId');
		if(!empty($id)){
			return true;
		}
		return false;
	}

}